import Router from '@koa/router'
import { z } from 'zod'
import { prisma } from '../../app'
import { createError } from '../../middleware/errorHandler'

const router = new Router()

// 验证 schema
const getPostsQuerySchema = z.object({
    page: z.string().optional().transform(val => val ? parseInt(val) : 1),
    limit: z.string().optional().transform(val => val ? parseInt(val) : 10),
    status: z.enum(['DRAFT', 'PUBLISHED', 'ARCHIVED']).optional(),
    authorId: z.string().optional(),
    search: z.string().optional()
})

const createPostSchema = z.object({
    title: z.string().min(1, 'Title is required').max(200, 'Title must be at most 200 characters'),
    content: z.string().min(1, 'Content is required'),
    summary: z.string().optional(),
    cover: z.string().url().optional(),
    status: z.enum(['DRAFT', 'PUBLISHED']).default('DRAFT'),
    tagIds: z.array(z.string()).optional()
})

const updatePostSchema = createPostSchema.partial()

const getPostByIdSchema = z.object({
    id: z.string().min(1, 'Post ID is required')
})

// 获取文章列表
router.get('/', async (ctx) => {
    try {
        const query = getPostsQuerySchema.parse(ctx.query)
        const { page, limit, status, authorId, search } = query

        const skip = (page - 1) * limit

        // 构建查询条件
        const where: any = {}

        if (status) {
            where.status = status
        } else {
            // 默认只显示已发布的文章（除非指定了作者ID）
            if (!authorId) {
                where.status = 'PUBLISHED'
            }
        }

        if (authorId) {
            where.authorId = authorId
        }

        if (search) {
            where.OR = [
                { title: { contains: search } },
                { summary: { contains: search } },
                { content: { contains: search } }
            ]
        }

        // 获取文章总数
        const total = await prisma.post.count({ where })

        // 获取文章列表
        const posts = await prisma.post.findMany({
            where,
            skip,
            take: limit,
            select: {
                id: true,
                title: true,
                summary: true,
                cover: true,
                status: true,
                views: true,
                likes: true,
                createdAt: true,
                updatedAt: true,
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                tags: {
                    select: {
                        tag: {
                            select: {
                                id: true,
                                name: true,
                                color: true
                            }
                        }
                    }
                },
                _count: {
                    select: {
                        comments: true
                    }
                }
            },
            orderBy: {
                createdAt: 'desc'
            }
        })

        // 格式化标签数据
        const formattedPosts = posts.map(post => ({
            ...post,
            tags: post.tags.map(pt => pt.tag)
        }))

        ctx.body = {
            success: true,
            message: 'Posts retrieved successfully',
            data: {
                posts: formattedPosts,
                pagination: {
                    page,
                    limit,
                    total,
                    totalPages: Math.ceil(total / limit),
                    hasNext: page * limit < total,
                    hasPrev: page > 1
                }
            }
        }
    } catch (error) {
        throw error
    }
})

// 根据ID获取文章详情
router.get('/:id', async (ctx) => {
    try {
        const { id } = getPostByIdSchema.parse(ctx.params)

        const post = await prisma.post.findUnique({
            where: { id },
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                tags: {
                    select: {
                        tag: {
                            select: {
                                id: true,
                                name: true,
                                color: true
                            }
                        }
                    }
                },
                comments: {
                    where: {
                        parentId: null
                    },
                    select: {
                        id: true,
                        content: true,
                        createdAt: true,
                        author: {
                            select: {
                                id: true,
                                username: true,
                                nickname: true,
                                avatar: true
                            }
                        },
                        replies: {
                            select: {
                                id: true,
                                content: true,
                                createdAt: true,
                                author: {
                                    select: {
                                        id: true,
                                        username: true,
                                        nickname: true,
                                        avatar: true
                                    }
                                }
                            }
                        }
                    },
                    orderBy: {
                        createdAt: 'desc'
                    }
                }
            }
        })

        if (!post) {
            throw createError.notFound('Post not found')
        }

        // 增加阅读量
        await prisma.post.update({
            where: { id },
            data: {
                views: {
                    increment: 1
                }
            }
        })

        // 格式化标签数据
        const formattedPost = {
            ...post,
            tags: post.tags.map(pt => pt.tag)
        }

        ctx.body = {
            success: true,
            message: 'Post retrieved successfully',
            data: formattedPost
        }
    } catch (error) {
        throw error
    }
})

// 创建文章（需要认证）
router.post('/', async (ctx) => {
    try {
        if (!ctx.user) {
            throw createError.unauthorized('User not authenticated')
        }

        const postData = createPostSchema.parse(ctx.request.body)
        const { tagIds, ...createData } = postData

        const post = await prisma.post.create({
            data: {
                ...createData,
                authorId: ctx.user.userId,
                tags: tagIds ? {
                    create: tagIds.map(tagId => ({ tagId }))
                } : undefined
            },
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                tags: {
                    select: {
                        tag: {
                            select: {
                                id: true,
                                name: true,
                                color: true
                            }
                        }
                    }
                }
            }
        })

        // 格式化标签数据
        const formattedPost = {
            ...post,
            tags: post.tags.map(pt => pt.tag)
        }

        ctx.body = {
            success: true,
            message: 'Post created successfully',
            data: formattedPost
        }
    } catch (error) {
        throw error
    }
})

export default router
